package com.example.demo;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.net.URISyntaxException;
import static com.example.demo.Content.clientId;

@Slf4j
@Component
public class TestScheduled {

    private CustomizedWebSocketClient customizedWebSocketClient;

    @PostConstruct
    public void init() throws URISyntaxException {
        //懒汉模式创建客户端连接
        customizedWebSocketClient = WebSocketClientSingleton.getInstance();
    }

    //模拟发送设备信息，目前只发送当前时间
//    @Scheduled(cron = "0/1 * * * * ?")
    public void test() throws URISyntaxException {
        // 用hultool工具获得当前时间字符串
        String currentTimeStr = DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss");
        // 客户端发送消息
        if (customizedWebSocketClient.isClosed()) {
            customizedWebSocketClient = WebSocketClientSingleton.getInstance();
        }
        Message message = Message.builder().type("time").data("{\"id\":\"" + clientId + "\",\"data\":\"" + currentTimeStr + "\"}").build();
        customizedWebSocketClient.sendMessage(JSONUtil.toJsonStr(message));
    }
}